import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getDatasourceList } from '@/api/datasource'
import { generateFakeData } from '@/api/fake-data'

export default function useFakeData() {
  // 表单引用
  const formRef = ref(null)

  // SQL预览标签页
  const sqlTab = ref('create')

  // 数据源选项
  const datasourceOptions = ref([])

  // 表单数据
  const form = reactive({
    datasource_type: 'mysql',
    table_name: '',
    record_count: 100,
    fields: [
      {
        name: 'id',
        type: 'id',
      },
      {
        name: 'name',
        type: 'name',
      },
      {
        name: 'age',
        type: 'integer',
        min: 18,
        max: 65
      },
      {
        name: 'email',
        type: 'email'
      },
      {
        name: 'create_time',
        type: 'datetime',
        start_date: '2023-01-01 00:00:00',
        end_date: '2023-12-31 23:59:59'
      }
    ],
    generate_sql: true,
    generate_to_datasource: false,
    datasource_id: ''
  })

  // 表单校验规则
  const rules = {
    datasource_type: [
      { required: true, message: '请选择数据源类型', trigger: 'change' }
    ],
    table_name: [
      { required: true, message: '请输入表名', trigger: 'blur' }
    ],
    record_count: [
      { required: true, message: '请输入记录数量', trigger: 'blur' }
    ],
    datasource_id: [
      { required: true, message: '请选择数据源', trigger: 'change' }
    ]
  }

  // 生成结果
  const generateResult = ref({
    success: false,
    table_name: '',
    record_count: 0,
    field_count: 0,
    datasource_name: '',
    preview_data: [],
    create_sql: '',
    insert_sql: ''
  })

  // 获取数据源列表
  const getDatasources = async () => {
    try {
      const res = await getDatasourceList({ page: 1, size: 1000 })
      datasourceOptions.value = res.data.filter(item => item.type === form.datasource_type)
    } catch (error) {
      console.error('获取数据源列表失败:', error)
    }
  }

  // 添加字段
  const addField = () => {
    form.fields.push({
      name: '',
      type: 'string',
      min_length: 1,
      max_length: 10
    })
  }

  // 移除字段
  const removeField = (index) => {
    form.fields.splice(index, 1)
  }

  // 处理字段类型变化
  const handleFieldTypeChange = (index) => {
    const field = form.fields[index]
    
    // 根据字段类型设置默认值
    switch (field.type) {
      case 'integer':
        field.min = 0
        field.max = 1000
        break
      case 'float':
        field.min = 0
        field.max = 1000
        field.precision = 2
        break
      case 'string':
        field.min_length = 1
        field.max_length = 10
        break
      case 'datetime':
        const now = new Date()
        const startDate = new Date()
        startDate.setFullYear(now.getFullYear() - 1)
        
        field.start_date = formatDate(startDate)
        field.end_date = formatDate(now)
        break
      case 'enum':
        field.values = 'value1,value2,value3'
        break
    }
  }

  // 格式化日期
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const res = await generateFakeData(form)
          generateResult.value = res.data
          generateResult.value.success = true
          
          ElMessage.success('数据生成成功')
        } catch (error) {
          console.error('生成数据失败:', error)
        }
      }
    })
  }

  // 重置表单
  const resetForm = () => {
    if (!formRef.value) return
    formRef.value.resetFields()
    
    // 重置生成结果
    generateResult.value.success = false
  }

  // 下载SQL
  const downloadSql = () => {
    const createSql = generateResult.value.create_sql
    const insertSql = generateResult.value.insert_sql
    const content = `${createSql}\n\n${insertSql}`
    
    downloadFile(`${form.table_name}.sql`, content)
  }

  // 下载CSV
  const downloadCsv = () => {
    const fields = form.fields.map(field => field.name)
    const data = generateResult.value.preview_data
    
    // 生成CSV内容
    let csvContent = fields.join(',') + '\n'
    
    data.forEach(row => {
      const rowValues = fields.map(field => {
        const value = row[field]
        
        // 处理包含逗号的字符串
        if (typeof value === 'string' && value.includes(',')) {
          return `"${value}"`
        }
        
        return value
      })
      
      csvContent += rowValues.join(',') + '\n'
    })
    
    downloadFile(`${form.table_name}.csv`, csvContent)
  }

  // 下载文件
  const downloadFile = (filename, content) => {
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    link.click()
    
    URL.revokeObjectURL(url)
  }

  // 监听数据源类型变化
  watch(() => form.datasource_type, () => {
    // 更新数据源选项
    getDatasources()
    
    // 清空已选数据源
    form.datasource_id = ''
  })

  onMounted(() => {
    getDatasources()
  })

  return {
    formRef,
    sqlTab,
    datasourceOptions,
    form,
    rules,
    generateResult,
    addField,
    removeField,
    handleFieldTypeChange,
    submitForm,
    resetForm,
    downloadSql,
    downloadCsv
  }
}